import jieba.analyse as ana
from models.models import CustomerReply
from django.http.response import JsonResponse
from models.models.RequestResult import RequestResult as Res
from django.views.decorators.csrf import csrf_exempt
from django.core.cache import cache


@csrf_exempt
def reply(request):
    print("=================开始智能回复=====================")
    # 获取问题
    issue = request.POST.get("issue")
    # 如果数据库中没有当前问题，添加
    cr = CustomerReply.objects.filter(keyword=issue)
    if len(cr) == 0:
        cr = CustomerReply()
        cr.keyword = issue
        cr.save()
    # 解析出关键字
    keywords = ana.tfidf(issue)
    print("关键字", keywords)
    # 根据关键字模糊查询出所有结果
    customerReplyList = list()
    for keyword in keywords :
        customerReply = CustomerReply.objects.filter(keyword__contains=keyword,reply__isnull=False)
        customerReplyList.extend(customerReply)
    print(customerReplyList)
    # 统计每条数据出现的次数
    count = dict()
    customerReplyDict = dict()
    for customerReply in customerReplyList :
        if count.get(customerReply.id) is None:
            count[customerReply.id] = 0
        count[customerReply.id] += 1
        customerReplyDict[customerReply.id] = customerReply
    print(count)
    # 统计出现次数最多的数据id
    maxIds = list()
    maxNum = 0
    for id in count.keys():
        if maxNum < count[id]:
            maxNum = count[id]
    for id in count.keys():
        if maxNum == count[id]:
            maxIds.append(id)
    # 统计出现次数最多的数据
    customerReplyMaxList = list()
    for id in maxIds:
        customerReplyMaxList.append(customerReplyDict[id])
    # 将关键字拼接
    keywordStr = ""
    for k in keywords:
        keywordStr += k
    # 匹配customerReplyMaxList中长度最和keywordStr长度相近的一个
    resCustomerReply = None
    minLen = 999999999999
    for customerReply in customerReplyMaxList:
        lenNum = len(customerReply.keyword) - len(keywordStr)
        lenNum = abs(lenNum)
        if minLen > lenNum:
            minLen = lenNum
            resCustomerReply = customerReply
    print("=================结束智能回复=====================")
    if resCustomerReply is not None:
        return JsonResponse(Res.success(resCustomerReply.reply))
    return JsonResponse(Res.success("对不起，小智还不能理解您的问题。"))
